package tool;

import java.io.IOException;
import java.util.Enumeration;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;

import function.Mp3File;

import playlist.Crawler;

public class FileConnectionUtils {

	private static final String NOW_DIR = Path.NOW;
	
	public static String[] getMp3sList(String dir) {

		int size = getNumMp3(dir);
		String[] mp3s = new String[size];

		FileConnection connection;
		try {
			connection = (FileConnection) Connector.open(dir);
			Enumeration mp3Enum = connection.list("*.mp3", true);

			for (int i = 0; i < mp3s.length; i++) {
				mp3s[i] = (String) mp3Enum.nextElement();
			}
			connection.close();
		} catch (IOException e) {
			Crawler.alert(e);
			e.printStackTrace();
		}
		return mp3s;
	}

	public static int getNumMp3(String dir) {
		return getNum(dir, "*.mp3");
	}
	
	public static int getNum(String dir, String filter) {
		FileConnection connection;
		int index = 0;

		try {
			connection = (FileConnection) Connector.open(dir);
			Enumeration files = connection.list(filter, true);

			while (files.hasMoreElements()) {
				String mp3 = (String) files.nextElement();
				index++;
			}
			connection.close();
		} catch (IOException e) {
			Crawler.alert(e);
			e.printStackTrace();
		}
		return index;
	}

	public static void secureDelete(Mp3File mp3) {
		if (Path.BOOT.equals(mp3.getDir())) {			
			try {
				String title = mp3.getTitle();
				FileConnection connection
					= (FileConnection) Connector.open(
					Path.NOW + "/" + title + ".link");
				connection.rename(mp3.getTitle() + ".delete");
			} catch (Throwable e) {
				e.printStackTrace();
			}
		}
	}

	public static String[] getNowMp3sList() {
		int size = getNum(Path.NOW, "*.link");
		String[] mp3s = new String[size];

		FileConnection connection;
		try {
			connection = (FileConnection) Connector.open(Path.NOW);
			Enumeration mp3Enum = connection.list("*.link", true);

			for (int i = 0; i < mp3s.length; i++) {
				String rawName = (String) mp3Enum.nextElement();
				mp3s[i] = rawName.substring(0, 
					rawName.length() - 5) + ".mp3";
			}
			connection.close();
		} catch (IOException e) {
			Crawler.alert(e);
			e.printStackTrace();
		}
		return mp3s;
	}
}
